package com.ruoyi.course.service.impl;
import com.ruoyi.common.utils.VideoDurationUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;
import com.ruoyi.course.mapper.CourseVideosMapper;
import com.ruoyi.course.domain.CourseVideos;
import com.ruoyi.course.service.ICourseVideosService;

import java.io.File;
import java.util.List;


/**
 * 课程视频关联Service业务层处理
 *
 * @author ruoyi
 * @date 2025-08-13
 */
@Service
public class CourseVideosServiceImpl implements ICourseVideosService
{
    @Autowired
    private CourseVideosMapper courseVideosMapper;
    @Value("${ruoyi.profile}")
    private String profile;


    private String getDatePath(String videoUrl) {
        String[] parts = videoUrl.split("/");
        if (parts.length >= 3) {
            return parts[0] + "/" + parts[1] + "/" + parts[2]; // 得到"2025/08/13"
        }
        return "";
    }

    // 拼接完整路径的核心方法
    private String getFullVideoPath(String videoUrl) {

        String datePath = getDatePath(videoUrl);

        // 2. 提取文件名（如"xxx.mp4"）
        String fileName = videoUrl.substring(videoUrl.lastIndexOf("/") + 1);

        // 3. 拼接完整路径：前缀 + 日期路径 + 文件名
        // 使用File类自动处理分隔符
        File fullPath = new File(new File(profile, datePath), fileName);
        System.out.println("完整路径：" + fullPath);
        return fullPath.getAbsolutePath();
    }
    /**
     * 新增课程视频关联（自动补充时长）
     */
    @Override
    public int insertCourseVideos(CourseVideos courseVideos) {
        if (courseVideos.getVideoUrl() != null && courseVideos.getDuration() == null) {
            // 拼接完整路径
            String fullPath = getFullVideoPath(courseVideos.getVideoUrl());

            // 获取时长并设置
            String duration = VideoDurationUtil.getVideoDuration(fullPath);
            if (duration != null) {
                courseVideos.setDuration(duration);
            }
        }
        return courseVideosMapper.insertCourseVideos(courseVideos);
    }


    /**
     * 查询单个视频时确保时长存在
     */
    @Override
    public CourseVideos selectCourseVideosById(String id) {
        CourseVideos video = courseVideosMapper.selectCourseVideosById(id);
        // 补全时长（如果为空）
        if (video != null && (video.getDuration() == null || video.getDuration().isEmpty()) && video.getVideoUrl() != null) {
            String duration = VideoDurationUtil.getVideoDuration(
                    video.getVideoUrl().startsWith("http") ?
                            video.getVideoUrl() :
                            profile + video.getVideoUrl()
            );
            if (duration != null) {
                video.setDuration(duration);
                // 更新数据库
                courseVideosMapper.updateCourseVideos(video);
            }
        }
        return video;
    }

    /**
     * 查询视频列表时补全时长
     */
    @Override
    public List<CourseVideos> selectCourseVideosList(CourseVideos courseVideos) {
        List<CourseVideos> videos = courseVideosMapper.selectCourseVideosList(courseVideos);
        for (CourseVideos video : videos) {
            if ((video.getDuration() == null || video.getDuration().isEmpty()) && video.getVideoUrl() != null) {
                String duration = VideoDurationUtil.getVideoDuration(
                        video.getVideoUrl().startsWith("http") ?
                                video.getVideoUrl() :
                                profile + video.getVideoUrl()
                );
                if (duration != null) {
                    video.setDuration(duration);
                    // 异步更新数据库（避免影响列表查询性能）
                    new Thread(() -> courseVideosMapper.updateCourseVideos(video)).start();
                }
            }
        }
        return videos;
    }

    // 其他方法保持不变
    @Override
    public int updateCourseVideos(CourseVideos courseVideos) {
        // 如果更新了视频URL，重新计算时长
        if (courseVideos.getVideoUrl() != null) {
            String duration = VideoDurationUtil.getVideoDuration(
                    courseVideos.getVideoUrl().startsWith("http") ?
                            courseVideos.getVideoUrl() :
                            profile + courseVideos.getVideoUrl()
            );
            if (duration != null) {
                courseVideos.setDuration(duration);
            }
        }
        return courseVideosMapper.updateCourseVideos(courseVideos);
    }

    @Override
    public int deleteCourseVideosByIds(String[] ids) {
        return courseVideosMapper.deleteCourseVideosByIds(ids);
    }

    @Override
    public int deleteCourseVideosById(String id) {
        return courseVideosMapper.deleteCourseVideosById(id);
    }
}